package com.fourth.controller;


import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.fourth.entity.Cart;
import com.fourth.entity.Pay;
import com.fourth.entity.User;
import com.fourth.service.OrdersService;
import com.fourth.service.UserService;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.*;

@RestController
@RequestMapping("/front")
public class UserController {
    @Resource
    UserService userService;

    @Resource
    OrdersService ordersService;

    //沙箱应用的APPID
    private final String APP_ID = "2016103000777820";
    //生成的应用私钥
    private final String APP_PRIVATE_KEY = "MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQCFSlvBtegj95x6hcdjpo7QvedTsctFhJqbZcV551vd6Sgz3Kl+XNInkmcx/VOKjFmn/t9YLCQE1vEtgGLJx1Tkwi5v6W+AgXk5UR+TJNcRR2nqs19Usdchrz+J8gAgQkcDjrpUwDQlvGNGRx8xD4m7ufHCxF+WUpK57PvgIW9nR6nm+kAYi482afpJWnJWw0M1I6zGOikxFQHeo2OHLq1BWl4llokdx8xQ2AXzoTdAvv9anMf3YX2P0fr2Dq4B3Mxrh6wf5cEfl8Rn1GYaafpzbdSr71QVTEFkTmRYnAFb9narWiTLfVdnixxRiJ5WR6MZzNg/BOyWgspaCR534aDtAgMBAAECggEAIFHGa/MCxe3dWGwly8jwKjdR5x5eTo33uyRzPLrXsLg/Ukv4ITa6knPSZ/GoFxkvCCgp2cRiO3Yu5ryRt6GIuStIfURaEAvU7Av6nwA40ezCBvHVdMDmjDllK7qtQyUu+PLbxX8RZfEHFVxbeNb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QC/uGo2/WPKI=";
    private final String CHARSET = "UTF-8";
    //支付宝公钥
    private final String ALIPAY_PUBLIC_KEY = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA5NAYdygNR2OMTSZbTm6ganKk1h6UqKwpcSv3kVGQwE8QJyENhP9bn3jWibghEeObrhoy7wTnwSucSXYSHm4PDqWyy+pLrMNqwtHxaK9Bv0jrK6nHbjkU9777d2G7grtrPW8eY1W0aND+H9wDPU/tQCVpRWYSu9Jn44X3EuDfDtkJkM3dMNtpRZgT+6QGDEv8mO1UrusUstgrPvJsWw7XDBUsz+Ynt//lgJVPbIRsep9i+g4ws6fDGDoNIdR0P0S5PjwtQBI+0mSnyCE+/41Bl7j37Zak4FTTnjj2ZUbY1w+3PGQr356C0qYet3FJcDb+R8R+N8tzU5O4WTZqlXm92QIDAQAB";
    //这是沙箱接口路径,正式路径为https://openapi.alipay.com/gateway.do
    private final String GATEWAY_URL ="https://openapi.alipaydev.com/gateway.do";
    private final String FORMAT = "JSON";
    //签名方式
    private final String SIGN_TYPE = "RSA2";
    //支付宝异步通知路径,付款完毕后会异步调用本项目的方法,必须为公网地址
    private final String NOTIFY_URL = "http://localhost:8080/front/notifyUrl";
    //支付宝同步通知路径,也就是当付款完毕后跳转本项目的页面,可以不是公网地址
    private final String RETURN_URL = "http://localhost:8080/front/returnUrl";

    @RequestMapping("/selectAllUser")
    public List<User> selectAllUser(){
        return userService.selectAllUser();
    }

    /**
     * 登录
     * @param uName
     * @param uPassword
     * @param session
     * @return
     */
    @RequestMapping("/login")
    public String login(@RequestParam("uName") String uName, @RequestParam("uPassword") String uPassword,
                        HttpSession session){

        User user = userService.login(uName, uPassword);
        if(user==null){
            return "登录失败";
        }

        Integer uStatus = user.getUStatus();
        if(uStatus==0){
            return "用户已被冻结";
        }else {
            session.setAttribute("uId",user.getUId());
            session.setAttribute("uName",user.getUName());

            int uid=user.getUId();
            ArrayList<Cart> myCart = (ArrayList<Cart>) session.getAttribute("myCart");

            String s = userService.mergeCartDate(myCart, uid);

            return "登录成功";
        }

    }

    /**
     * 判断用户注册名是否符合规范
     * @param uName
     * @return
     */
    @RequestMapping("/checkUserNorm")
    public String checkUserNorm(@RequestParam("uName") String uName){

        String normAll = userService.checkUsername(uName);

        String s = userService.selectUserByuName(uName);

        System.out.println(normAll+"-"+s);
        return normAll+"-"+s;


    }

    /**
     * 检查两次密码输入是否相同
     * @param password
     * @param repassword
     * @return
     */
    @RequestMapping("/checkPassword")
    public String checkPassword(@RequestParam("password") String password, @RequestParam("repassword") String repassword){
        String s = userService.checkPassword(password, repassword);
        return s;
    }

    /**
     * 检查邮箱规范
     * @param email
     * @return
     */
    @RequestMapping("/checkEmail")
    public String checkEmail(@RequestParam("email") String email){
        System.out.println(email);
        String s = userService.checkEmail(email);
        System.out.println(s);
        return s;
    }

    /**
     * 注册
     * @param user
     * @return
     */
    @RequestMapping("/register")
    public String register(User user, String repassword){
        String register = userService.register(user,repassword);
        return register;
    }

    /**
     * 检查电话号码是否符合规范
     * @param phone
     * @return
     */
    @RequestMapping("/checkPhone")
    String checkPhone(String phone){
        String s = userService.checkPhone(phone);
        return s;
    }


    /**
     * 发送验证码
     * @param phone
     * @param session
     * @return
     */
    @RequestMapping("/dateCodeSend")
    public String dateCodeSend(String phone, HttpSession session){
        String s = userService.checkPhone(phone);
        if(s.equals("phoneUnable")){
            return "phoneUnable";
        }else {
            String s1 = userService.dateCodeSend(phone);
            String[] split = s1.split("-");

            if(split[1].equals("false")){
                return "sendDefeat";
            }else {
                System.setProperty("dateCode",split[0]);
                return "sendSuccess";
            }
        }
    }

    /**
     * 检查验证码
     * @param dateCode
     * @return
     */
    @RequestMapping("/checkDateCode")
    public String checkDateCode(String dateCode){

        System.out.println(dateCode);

        String date1=System.getProperty("dateCode");
        System.out.println(date1);

        System.out.println(dateCode.equals(date1));

        if(dateCode.equals(date1)){
            return "dateCodeUsable";
        }else {
            return "dateCodeUnable";
        }
    }

    @RequestMapping("/outLogin")
    public String outLogin(HttpSession session){
        session.removeAttribute("uId");
        session.removeAttribute("uName");
        session.removeAttribute("myCart");
        return "登出成功";
    }

    @RequestMapping("/aliPay")
    public void aliPay(HttpServletResponse httpResponse, String oNo, String totalPrice){
        Random r=new Random();
        //实例化客户端,填入所需参数
        AlipayClient alipayClient = new DefaultAlipayClient(GATEWAY_URL, APP_ID, APP_PRIVATE_KEY, FORMAT, CHARSET, ALIPAY_PUBLIC_KEY, SIGN_TYPE);
        AlipayTradePagePayRequest request = new AlipayTradePagePayRequest();
        //在公共参数中设置回跳和通知地址
        request.setReturnUrl(RETURN_URL);
        request.setNotifyUrl(NOTIFY_URL);
        //商户订单号，商户网站订单系统中唯一订单号，必填
        //生成随机Id
        String out_trade_no=new String();
        String total_amount =new String();
        if(oNo==null){
            out_trade_no = UUID.randomUUID().toString();
        }else {
            out_trade_no=oNo;
        }

        if(totalPrice==null){
            total_amount="30";
        }else {
            total_amount=totalPrice;
        }

        //付款金额，必填
//        String total_amount =Integer.toString(r.nextInt(99)+10);

        //订单名称，必填
        String subject ="小红帽";
        //商品描述，可空
//        String body = "尊敬的会员欢迎购买奥迪A8-2016款-A8L-60-TFSl-quattro豪华型";
        request.setBizContent("{\"out_trade_no\":\""+ out_trade_no +"\","
                + "\"total_amount\":\""+ total_amount +"\","
                + "\"subject\":\""+ subject +"\","
//                + "\"body\":\""+ body +"\","
                + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");
        String form = "";
        try {
            form = alipayClient.pageExecute(request).getBody(); // 调用SDK生成表单
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        httpResponse.setContentType("text/html;charset=" + CHARSET);

        try {
            httpResponse.getWriter().write(form);// 直接将完整的表单html输出到页面
            httpResponse.getWriter().flush();
            httpResponse.getWriter().close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @RequestMapping(value = "/returnUrl", method = RequestMethod.GET)
    public String returnUrl(HttpServletRequest request, HttpServletResponse response)
            throws IOException, AlipayApiException {
        System.out.println("=================================同步回调=====================================");

        // 获取支付宝GET过来反馈信息
        Map<String, String> params = new HashMap<String, String>();
        Map<String, String[]> requestParams = request.getParameterMap();
        for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext(); ) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i] : valueStr + values[i] + ",";
            }
            // 乱码解决，这段代码在出现乱码时使用
            valueStr = new String(valueStr.getBytes("utf-8"), "utf-8");
            params.put(name, valueStr);
        }

        System.out.println(params);//查看参数都有哪些
        boolean signVerified = AlipaySignature.rsaCheckV1(params, ALIPAY_PUBLIC_KEY, CHARSET, SIGN_TYPE); // 调用SDK验证签名
        //验证签名通过
        if (signVerified) {
            // 商户订单号
            String out_trade_no = new String(request.getParameter("out_trade_no").getBytes("ISO-8859-1"), "UTF-8");

            // 支付宝交易号
            String trade_no = new String(request.getParameter("trade_no").getBytes("ISO-8859-1"), "UTF-8");

            // 付款金额
            String total_amount = new String(request.getParameter("total_amount").getBytes("ISO-8859-1"), "UTF-8");

            BigDecimal pPrice=new BigDecimal(total_amount);

            System.out.println("商户订单号=" + out_trade_no);
            System.out.println("支付宝交易号=" + trade_no);
            System.out.println("付款金额=" + total_amount);
            System.out.println("付款金额=" + pPrice);
            //支付成功，修复支付状态
//            payService.updateById(Integer.valueOf(out_trade_no));
            //修改订单表支付状态
            int i = ordersService.changOrderStatus(out_trade_no);
            System.out.println("修改订单状态"+i);

            //支付成功添加支付流水

            Pay pay =new Pay();
            pay.setONo(out_trade_no);
            pay.setPNt(trade_no);
            pay.setPPrice(pPrice);
            pay.setPStatus("1");
            int i1 = userService.insertPayRecord(pay);
            System.out.println("插入支付流水账"+i1);

            return "<meta http-equiv='refresh' content=0;URL='http://localhost:8080/showOrder'>";//跳转付款成功页面
        } else {
            return "<meta http-equiv='refresh' content=0;URL='http://localhost:8080/showOrder'>";//跳转付款失败页面
        }
    }




}
